import { defineStore } from "pinia";
import { ref, computed, readonly } from "vue";
import { loginApi, refreshTokenApi } from "@/api/auth";

// 生成mock JWT token的辅助函数
const generateMockJWT = (payload = {}) => {
  const header = {
    alg: "HS256",
    typ: "JWT",
  };

  const defaultPayload = {
    sub: "1234567890",
    name: payload.username || "Mock User",
    iat: Math.floor(Date.now() / 1000),
    exp: Math.floor(Date.now() / 1000) + 24 * 60 * 60, // 24小时后过期
    ...payload,
  };

  // 简单的base64编码（仅用于mock，生产环境应使用真实的JWT库）
  const encodedHeader = btoa(JSON.stringify(header));
  const encodedPayload = btoa(JSON.stringify(defaultPayload));
  const signature = "mock-signature"; // 在真实环境中这应该是真实的签名

  return `${encodedHeader}.${encodedPayload}.${signature}`;
};

export const useAuthStore = defineStore(
  "auth",
  () => {
    // 状态
    const token = ref(localStorage.getItem("token") || "");
    const userInfo = ref(
      JSON.parse(localStorage.getItem("userInfo") || "null")
    );
    const isLoading = ref(false);

    // 计算属性
    const isAuthenticated = computed(() => {
      return !!token.value && !!userInfo.value;
    });

    // 获取token的getter
    const getToken = computed(() => token.value);

    // 设置token
    const setToken = (newToken) => {
      token.value = newToken;
      if (newToken) {
        localStorage.setItem("token", newToken);
      } else {
        localStorage.removeItem("token");
      }
    };

    // 设置用户信息
    const setUserInfo = (info) => {
      userInfo.value = info;
      if (info) {
        localStorage.setItem("userInfo", JSON.stringify(info));
      } else {
        localStorage.removeItem("userInfo");
      }
    };

    // 设置加载状态
    const setLoading = (loading) => {
      isLoading.value = loading;
    };

    // 登录
    const login = async (loginData) => {
      try {
        setLoading(true);

        let response;

        // 检查是否使用Mock数据
        if (import.meta.env.VITE_USE_MOCK === "true") {
          // 模拟登录响应，使用有效的JWT格式
          response = {
            token: generateMockJWT({
              username: loginData.username,
              email: loginData.email || `${loginData.username}@example.com`,
              roles: ["user"],
            }),
            userInfo: {
              id: 1,
              username: loginData.username,
              email: loginData.email || `${loginData.username}@example.com`,
              avatar: "",
              roles: ["user"],
            },
          };
        } else {
          // 调用真实的登录API
          response = await loginApi(loginData);
        }

        setToken(response.token);
        setUserInfo(response.userInfo);

        return { success: true, data: response };
      } catch (error) {
        console.error("登录失败:", error);
        return { success: false, error: error.message || "登录失败" };
      } finally {
        setLoading(false);
      }
    };

    // 登出
    const logout = () => {
      setToken("");
      setUserInfo(null);
      localStorage.clear();
      // 可以在这里添加其他清理逻辑
    };

    // 刷新token
    const refreshToken = async () => {
      try {
        let response;

        // 检查是否使用Mock数据
        if (import.meta.env.VITE_USE_MOCK === "true") {
          // 模拟刷新token响应，使用有效的JWT格式
          response = {
            token: generateMockJWT({
              username: userInfo.value?.username || "User",
              email: userInfo.value?.email || "user@example.com",
              roles: userInfo.value?.roles || ["user"],
            }),
          };
        } else {
          // 调用真实的刷新token API
          response = await refreshTokenApi();
        }

        setToken(response.token);
        return { success: true, token: response.token };
      } catch (error) {
        console.error("刷新token失败:", error);
        logout(); // 刷新失败则登出
        return { success: false, error: error.message || "刷新token失败" };
      }
    };

    // 检查token是否过期
    const checkTokenExpiry = () => {
      if (!token.value) return false;

      try {
        // 检查token格式是否为JWT (应该有3个部分，用.分隔)
        const tokenParts = token.value.split(".");
        if (tokenParts.length !== 3) {
          console.warn("Token格式不正确，不是有效的JWT");
          return true; // 格式不正确认为已过期
        }

        // 解析JWT token (简单实现，实际项目中可能需要更复杂的验证)
        const payload = JSON.parse(atob(tokenParts[1]));
        const currentTime = Date.now() / 1000;

        // 如果token即将在5分钟内过期，返回true
        return payload.exp && payload.exp - currentTime < 300;
      } catch (error) {
        console.error("解析token失败:", error);
        return true; // 解析失败认为已过期
      }
    };

    // 初始化认证状态
    const initAuth = () => {
      const storedToken = localStorage.getItem("token");
      const storedUserInfo = localStorage.getItem("userInfo");

      if (storedToken && storedUserInfo) {
        try {
          setToken(storedToken);
          setUserInfo(JSON.parse(storedUserInfo));

          // 检查token是否过期
          if (checkTokenExpiry()) {
            refreshToken();
          }
        } catch (error) {
          console.error("初始化认证状态失败:", error);
          logout();
        }
      }
    };

    return {
      // 状态
      token: readonly(token),
      userInfo: readonly(userInfo),
      isLoading: readonly(isLoading),

      // 计算属性
      isAuthenticated,
      getToken,

      // 方法
      setToken,
      setUserInfo,
      setLoading,
      login,
      logout,
      refreshToken,
      checkTokenExpiry,
      initAuth,
    };
  },
  {
    persist: {
      key: "auth-store",
      storage: localStorage,
      paths: ["token", "userInfo"],
    },
  }
);
